#!/bin/bash

# Simple, hacked-together database backup script

# Database name
DATABASE=$1

# Backup location 
LOCATION=$2

# Date 
DATE="$(date +%Y-%m-%d)"
TIME="$(date +%H-%M-%S)"

DATE_TIME="${DATE}_${TIME}"

# MySQL binary location of DB
MYSQL_DIR='/var/lib/mysql'
MYSQL_DB_DIR="${MYSQL_DIR}/${DATABASE}"

BACKUP_NAME="${DATABASE}_${DATE_TIME}"

# Check for free space 
FREE_INODES="$(df -ki ${LOCATION} | awk '/[0-9]%/ {print $3}')"
FREE_SPACE="$(df -k ${LOCATION} | awk '/[0-9]%/ {print $4}')"
NEEDED_SPACE="$(du -sk ${MYSQL_DB_DIR} | awk '{print $1}')"

if [[ $FREE_SPACE -gt $NEEDED_SPACE && $FREE_INODES -gt 100 ]]; then
    NAME="${LOCATION}/${BACKUP_NAME}"
    LOG_FILE='--log-error='"${NAME}.log"
    SQL_FILE='--result-file='"${NAME}.sql"
fi 

COMMAND="nice -n 5 mysqldump --add-locks --comments --complete-insert --dump-date --events --flush-logs --routines --tz-utc ${LOG_FILE}"

if [[ $3 == 'direct' ]]
  then 
    COMMAND="${COMMAND} ${DATABASE} | nice -5 gzip -c > ${NAME}.sql.gz"
  else
    COMMAND="${COMMAND} ${SQL_FILE} ${DATABASE} ; nice -5 gzip ${NAME}.sql" 
fi

if [[ $4 == 'run' || $3 == 'run' ]] 
  then
    eval "${COMMAND}"
  else
    echo 'Append "run" to execute backup.'
    echo 
    echo "${COMMAND}"
fi
